import { Box3Get, escapeHtml, get } from "@ap/util/request";
import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { auth } from "@ap/util/request";
import { updatePackageJson, getPackageJson } from "@ap/util/packageJson";
import { PackageConfig } from "@ap/types/config";
import { getGroupProject, STATIC_URL } from "./getGroupProject";
import { convertTimestampToDateString } from "./getMapStorage";
import { audioMap } from "@ap/command";
import { writeFile } from "@ap/util/fs";
import { tempPath } from "@ap/util/tempPath";
import path from "path";
import { transformDao3Resources } from "./transformDao3Resources";

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  view: string;
}

/**
 * 异步获取扩展地图音频列表数组。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function getMapAudioList(): Promise<
  ExtendedQuickPickItem[] | undefined
> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const response = await getGroupProject(mapId);
        if (!response) {
          return;
        }
        const requestOptions2 = {
          url: STATIC_URL + response.data.audioAssets,
        };
        const response2 = await get<Record<string, any>>(
          requestOptions2,
          "地图音频",
        );
        if (!response2) {
          showErrorMessage(`获取地图音频数据失败`);
          return;
        }
        /**+
         * 处理响应数据，映射物品到数据项格式，并转义HTML字符以防止XSS攻击。
         */
        let dataSource: ExtendedQuickPickItem[] = [];
        Object.entries(response2)
          .reverse()
          .forEach(([key, value]) => {
            dataSource.push({
              label: extractAudioFileName(key),
              description:
                value.size >= 1000000
                  ? (value.size / 1000000).toFixed(2).toString() + "MB"
                  : value.size
                    ? (value.size / 1000).toFixed(2).toString() + "KB"
                    : "",
              detail: convertTimestampToDateString(value.updateAt),
              view: STATIC_URL + value.hash,
            });
          });
        audioMap.description = `共${dataSource.length}项`;
        return dataSource;
      }
    }
  });
}

export function extractAudioFileName(path: string) {
  // 按斜杠分割字符串
  const parts = path.split("/");
  // 获取最后一个部分（文件名）
  const fileNameWithExtension = parts[parts.length - 1];
  return fileNameWithExtension;
}
